<template>
  <!-- 修改标签表单 -->
  <el-dialog
    :visible.sync="dialogVisible"
    width="40%"
    :title="title"
    @close="close">

    <el-form
      ref="categoryForm"
      :rules="categoryRules"
      status-icon
      :model="category"
      label-width="100px">

      <el-form-item label="分类名称：" prop="name">
        <el-input
          show-word-limit
          maxlength="20"
          v-model="category.name" />
      </el-form-item>

      <el-form-item label="分类排序：" prop="sort">
        <el-input-number :min="0" :max="999" v-model="category.sort" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="saveOrUpdate">确定</el-button>
    </div>

  </el-dialog>
</template>

<script>
  import { validNormal } from '@/utils/validate'
  import { getCategoryById, saveCategory, updateCategory } from '@/api/category'

  export default {
    data() {
      //检验分类名称
      const validateName = (rule, value, callback) => {
        if (value.length < 3 || value.length > 20 || !value || !validNormal(value)){
          callback(new  Error("请输入正确的课程分类，长度要求为3-20，且不能输入特殊字符"))
        }
        else callback()
      }

      return {
        title: '',
        dialogVisible: false,
        category: {
          id: '',
          name: '',
          parentId: '',
          sort: 0
        },
        //检验规则
        categoryRules:{
          name:[{validator: validateName,trigger: 'blur'}],
        }
      }
    },

    methods: {
      open(item) {
        this.dialogVisible = true

        //一级分类
        if (item.parent === '0'){
          //修改
          if (item.id){
            this.title = '修改一级课程分类'
            getCategoryById(item.id).then(result => {
              let { code, data } = result
              if (code === 20000){
                this.category = data.item
                delete this.category.gmtCreate
                delete this.category.gmtModified
              }
            })
          }
          else {
            this.title = '新增一级课程分类'
            delete this.category.parentId
          }
        }

        //二级分类
        else {
          //修改
          if (item.id){
            this.title = '修改二级课程分类'
            getCategoryById(item.id).then(result => {
              let { code, data } = result
              if (code === 20000){
                this.category = data.item
                delete this.category.gmtCreate
                delete this.category.gmtModified
              }
            })
          }
          else {
            this.title = '新增二级课程分类'
            this.category.parentId = item.parent
          }
        }
      },

      close() {
        this.$refs.categoryForm.resetFields();
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      resetForm() {
        this.category.id = ''
        this.category.name = ''
        this.category.sort = 0
        this.category.parentId = ''
      },

      saveOrUpdate() {
        this.$refs.categoryForm.validate((valid) => {
          if (valid) {
            //检验通过
            if (this.category.id){
              this.update()
            }
            else {
              this.save()
            }
          }
          else {
            return false;
          }
        })
      },

      save(){
        saveCategory(this.$qs.stringify(this.category)).then(result => {
          if (result.code === 20000){
            this.$message.success('新增成功！')
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          }
        })
      },

      update(){
        updateCategory(this.$qs.stringify(this.category)).then(result => {
          if (result.code === 20000){
            this.$message.success('修改成功！如分类存在同名，则不更新分类名称！')
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          }
        })
      }
    }

  }
</script>

<style scoped>

</style>
